package cn.cqk.v6.handle;

import cn.cqk.v6.enums.State;
import cn.cqk.v6.enums.Event;
import cn.cqk.v6.iface.IStateHandle;
import com.google.common.collect.HashBasedTable;
import lombok.Data;

import java.util.List;

abstract class AbstractStateMachine {

    @Data
    static class SopExec {
        private State nextState;
        private IStateHandle stateHandle;
    }

    private HashBasedTable<State, Event, SopExec> hashBasedTable = HashBasedTable.create();

    {
        List<SopProcess> sopProcesses = init();
        sopProcesses.forEach(item -> {
            SopExec sopExec = new SopExec();
            sopExec.setNextState(item.getTo());
            sopExec.setStateHandle(item.getStateHandle());
            hashBasedTable.put(item.getFrom(), item.getEvent(), sopExec);
        });
    }

    abstract List<SopProcess> init();

    public State getNextState(State state, Event event) {
        SopExec result = hashBasedTable.get(state, event);
        if (result == null) {
            throw new IllegalArgumentException("未找到状态");
        }
        return result.getNextState();
    }

    public IStateHandle getHandle(State state, Event event) {
        SopExec result = hashBasedTable.get(state, event);
        if (result == null) {
            throw new IllegalArgumentException("未找到状态");
        }
        return result.getStateHandle();
    }
}